# 读取文件，并生成词云
import re
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator

file = r'data.csv'


# 读取文件
def get_var(var):
    variable = []
    count = 0
    with open(file, 'r', encoding='utf-8') as fo:
        for i in fo:
            count += 1
            if count != 1:
                var1 = i.split(",")[var].replace("\n", "").replace("span", "").replace("class", "").replace("emoji", "")
                rep = re.compile("1fd+w*|[<>/=]")
                var1 = rep.sub("", var1)
                variable.append(var1)
    return variable


Signature = get_var(5)
text = "".join(Signature)

# 添加自己的词库分词，比如添加'小仙女'到jieba词库后，当你处理的文本中含有金三胖这个词，
# 就会直接将'小仙女'当作一个词，而不会得到'小仙'或'仙女'这样的词
# jieba.add_word('小仙女')
wordList = jieba.cut(text, cut_all=True)
word_space_split = " ".join(wordList)  # 这里必须是空格,否则图片会显示空白

# 设置词云样式
coloring = plt.imread("20170808173742917.bmp")  # 底图
my_wordcloud = WordCloud(background_color="white", max_words=800,  # 最大词数
                         mask=coloring, max_font_size=60, random_state=42,  # 为每个词返回一个PIL颜色
                         font_path=r"C:/Windows/Fonts/MSYHBD.TTC")
my_wordcloud.generate(word_space_split)
image_colors = ImageColorGenerator(coloring)

plt.imshow(my_wordcloud)
plt.axis('off')  # 关闭坐标轴
plt.figure()
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.axis('off')  # 关闭坐标轴
my_wordcloud.to_file(r"d:\temp.jpg")
# plt.show()  # 完成后弹出,并显示临时图片供选择
